package crp.core.portal.domain.services;

import crp.core.portal.domain.models.CreateNewsArticleCommand;
import crp.core.portal.domain.models.NewsArticleEntity;
import crp.core.portal.domain.models.UpdateNewsArticleCommand;
import crp.core.portal.domain.repositories.NewsArticleRepository;
import crp.core.shared.LifecycleStatus;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Optional;

@ApplicationScoped
public class NewsArticleEditor {
    private final NewsArticleRepository newsArticleRepository;

    @Inject
    public NewsArticleEditor(NewsArticleRepository newsArticleRepository) {
        this.newsArticleRepository = newsArticleRepository;
    }

    public NewsArticleEntity create(CreateNewsArticleCommand command) {
        NewsArticleEntity entity = command.of();
        newsArticleRepository.persist(entity);
        return entity;
    }

    public boolean delete(String id) {
        return newsArticleRepository.deleteById(id);
    }

    public Optional<NewsArticleEntity> update(UpdateNewsArticleCommand command) {
        Optional<NewsArticleEntity> may = newsArticleRepository.findByIdOptional(command.getId());
        may.ifPresent(entity -> {
            command.update(entity);
            newsArticleRepository.persist(entity);
        });
        return may;
    }

    public Optional<NewsArticleEntity> enable(String id) {
        Optional<NewsArticleEntity> may = newsArticleRepository.findByIdOptional(id);
        may.ifPresent(entity -> {
            entity.setStatus(LifecycleStatus.ENABLED);
            newsArticleRepository.persist(entity);
        });
        return may;
    }
}
